import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import { resolve } from 'path';
import { viteStaticCopy } from 'vite-plugin-static-copy'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import legacy from '@vitejs/plugin-legacy'

const pad = (number: number) => String(number).padStart(2, '0');

// 122 可能为 12.2、1.22 所以改为 122和1202
const date = new Date();
// 版本号点后不能0开头
const version = `8.${date.getFullYear()}.${date.getMonth() + 1}${pad(date.getDate())}.${date.getHours()}${pad(date.getMinutes())}`;
const BROWSER = process.env.BROWSER;

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  return {
    base: './',
    build: {
      target: 'es5',
      rollupOptions: {
        input: {
          panel: resolve(__dirname, 'panel/index.html'),
          content_script: resolve(__dirname, 'ext/content_script.ts'),
          service_worker: resolve(__dirname, 'ext/service_worker.ts')
        },
        output: {
          entryFileNames: (chunkInfo) => {
            console.log(chunkInfo);
            if (chunkInfo.name === 'service_worker' || chunkInfo.name === 'content_script') {
              return '[name].js';
            }
            return 'panel/js/[name].js';
          },
          chunkFileNames: 'panel/chunks/[name].js',
          assetFileNames: 'panel/assets/[name].[ext]'
        }
      },
      outDir: `dist-${BROWSER}`,
      emptyOutDir: true // 清空旧目录
    },
    publicDir: 'public', // 静态资源目录
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    plugins: [
      nodePolyfills({
        globals: {
          Buffer: true, // can also be 'build', 'dev', or false
          global: true,
          process: true,
        },
      }),
      react(),
      viteStaticCopy({
        targets: [
          {
            src: `ext/manifest-${BROWSER}.json`,
            dest: '', // 相对于outDir
            rename: 'manifest.json',
            transform: (manifest) => {
              const manifestJson = JSON.parse(manifest);
              manifestJson.version = version;
              if (mode === 'bate') {
                // 开发环境增加key验证
                manifestJson.key = 'privateKey';
              }
              return JSON.stringify(manifestJson, null, 2);
            }
          }
        ]
      }),
    ],
    // define: {
    // }
  }
})
